package com.dupf.product.rpc.service.impl;

import com.dupf.common.annotation.BaseService;
import com.dupf.common.base.BaseServiceImpl;
import com.dupf.common.util.ItvJsonUtil;
import com.dupf.common.util.RedisUtil;
import com.dupf.product.dao.mapper.ProductDetailMapper;
import com.dupf.product.dao.mapper.ProductInfoMapper;
import com.dupf.product.dao.model.ProductDetail;
import com.dupf.product.dao.model.ProductDetailExample;
import com.dupf.product.dao.model.ProductInfo;
import com.dupf.product.dao.model.ProductInfoExample;
import com.dupf.product.dao.smodel.ProductExportParamDTO;
import com.dupf.product.dao.smodel.ProductExportResultDTO;
import com.dupf.product.rpc.api.ProductInfoService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * ProductInfoService实现
 * Created by dupf on 2018/3/14.
 */
@Service
@Transactional
@BaseService
public class ProductInfoServiceImpl extends BaseServiceImpl<ProductInfoMapper, ProductInfo, ProductInfoExample> implements ProductInfoService {

    private static final Logger LOGGER = LoggerFactory.getLogger(ProductInfoServiceImpl.class);

    @Autowired
    ProductInfoMapper productInfoMapper;

    @Autowired
    ProductDetailMapper productDetailMapper;

    @Autowired
    ProductExportServiceImpl productExportService;

    public String exportProduct(ProductInfoExample productInfoExample, ProductExportParamDTO paramDTO) {

        productInfoExample.setOrderByClause("id DESC");
        List<ProductInfo> infos = productInfoMapper.selectByExample(productInfoExample);

        List<Integer> productIds = new ArrayList<>();
        infos.forEach(item -> {
            productIds.add(item.getId());
        });

        ProductDetailExample productDetailExample = new ProductDetailExample();
        productDetailExample.createCriteria().andProductIdIn(productIds);
        productDetailExample.setOrderByClause("product_id DESC");
        List<ProductDetail> details = productDetailMapper.selectByExampleWithBLOBs(productDetailExample);

        return productExportService.exportProduct(infos, details, paramDTO);
    }

    public List<ProductExportResultDTO> getExportProductList(ProductInfoExample productInfoExample, ProductExportParamDTO paramDTO) {

        productInfoExample.setOrderByClause("id DESC");
        List<ProductInfo> infos = productInfoMapper.selectByExample(productInfoExample);

        List<Integer> productIds = new ArrayList<>();
        infos.forEach(item -> {
            productIds.add(item.getId());
        });

        ProductDetailExample productDetailExample = new ProductDetailExample();
        productDetailExample.createCriteria().andProductIdIn(productIds);
        productDetailExample.setOrderByClause("product_id DESC");
        List<ProductDetail> details = productDetailMapper.selectByExampleWithBLOBs(productDetailExample);

        return productExportService.getExportProductList(infos, details, paramDTO);
    }

    public Integer createProduct(Integer userId, Integer orgId, JSONObject data) {
        JSONObject info = new JSONObject();

        info.put("title", data.opt("title"));
        info.put("mainPic", data.opt("mainPic"));
        info.put("category", data.opt("category"));
        info.put("categoryId", data.opt("categoryId"));
        info.put("sku", data.opt("sku"));
        info.put("costPrice", data.opt("costPrice"));
        info.put("costCurUnit", data.opt("costCurUnit"));
        info.put("salePrice", data.opt("salePrice"));
        info.put("saleCurUnit", data.opt("saleCurUnit"));
        info.put("sourceDomain", data.opt("sourceDomain"));
        info.put("sourceUrl", data.opt("sourceUrl"));
        info.put("productTag", data.opt("productTag"));
        info.put("status", data.opt("status"));

        data.put("title", null);
        data.put("mainPic", null);
        data.put("category", null);
        data.put("categoryId", null);
        data.put("sku", null);
        data.put("costPrice", null);
        data.put("costCurUnit", null);
        data.put("salePrice", null);
        data.put("saleCurUnit", null);
        data.put("sourceDomain", null);
        data.put("sourceUrl", null);
        data.put("productTag", null);
        data.put("status", null);

        ProductInfo productInfo = ItvJsonUtil.readValue(info.toString(), ProductInfo.class);
        productInfo.setOrgId(orgId);
        productInfo.setCollectUserId(userId);

        JSONArray variant = null;
        if (data.containsKey("variant")) {
            variant = data.getJSONArray("variant");
            data.put("variant", null);
        }

        JSONArray variantCompose = null;
        if (data.containsKey("variantCompose")) {
            variantCompose = data.getJSONArray("variantCompose");
            data.put("variantCompose", null);
        }

        ProductDetail productDetail = ItvJsonUtil.readValue(data.toString(), ProductDetail.class);

        if (productDetail.getTitleZh() != null) {
            productInfo.setTitle(productDetail.getTitleZh());
        }

        // 更新分类
//        if (!StringUtils.isEmpty(productInfo.getCategoryId())) {
//            productInfo.setCategory(productCategoryService.getCategoryByIds(productInfo.getCategoryId()));
//        }

        if (productInfo.getStatus() == null) {
            productInfo.setStatus((byte) 1);
        }

        // sku
        productInfo.setSku(String.valueOf(RedisUtil.incrementAndGet("product_sku", 1525330L, null)));

        // 产品编号
        productInfo.setProductNo(String.valueOf(RedisUtil.incrementAndGet("product_no", 15253L, null)));

        productInfo.setCtime(System.currentTimeMillis());
        this.insertSelective(productInfo);

        if (variant != null) {
            productDetail.setVariant(variant.toString());
        }

        if (variantCompose != null) {
            productDetail.setVariantCompose(variantCompose.toString());
        }

        productDetail.setProductId(productInfo.getId());

        productDetail.setCtime(System.currentTimeMillis());
        productDetailMapper.insertSelective(productDetail);
        return productInfo.getId();
    }

}